﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.Business.Sec;

namespace ESOL.WinUI.Pur
{
    public partial class frmMaintainPurchaseArrivedOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public PurPurchaseArrivedEntity SelectedPurchaseArrived { get; set; }
        private List<PurPurchaseArrivedItemEntity> DeleteList = new List<PurPurchaseArrivedItemEntity>();

        private List<PurPurchaseOrderEntity> mListPurchaseOrders;
        #endregion

        #region Constructor
        public frmMaintainPurchaseArrivedOrder()
        {
            InitializeComponent();
            if (SelectedPurchaseArrived == null)
            {
                SelectedPurchaseArrived = new PurPurchaseArrivedEntity();
                SelectedPurchaseArrived.ArrivedId = Guid.NewGuid().ToString();
            }
        }

        public frmMaintainPurchaseArrivedOrder(List<PurPurchaseOrderEntity> purOrder)
        {
            InitializeComponent();
            if (SelectedPurchaseArrived == null)
            {
                SelectedPurchaseArrived = new PurPurchaseArrivedEntity();
                SelectedPurchaseArrived.ArrivedId = Guid.NewGuid().ToString();
            }
            mListPurchaseOrders = purOrder;
        }
        #endregion

        #region Functions
        private void Init()
        {
            if (ThisActionType == ActionType.New)
            {
                gridView1.Columns["ARRIVED_QTY"].Caption = "已做到货量";
                gridView1.Columns["ARRIVED_QTY"].FieldName = "ARRIVED_HISTORY_QTY";
                gridView1.Columns["ARRIVED_HISTORY_QTY"].OptionsColumn.ReadOnly = true;
                gridView1.Columns["ARRIVED_HISTORY_QTY"].AppearanceHeader.ForeColor = Color.Black;
                gridView1.Columns["CUR_ARRIVE_QTY"].Caption = "此次到货量";
                gridView1.Columns["CUR_ARRIVE_QTY"].FieldName = "ARRIVED_QTY";
                gridView1.Columns["ARRIVED_QTY"].AppearanceHeader.ForeColor = Color.Red;
            }
            if (ThisActionType == ActionType.View || ThisActionType == ActionType.Modify)
            {
                gridView1.Columns["ARRIVED_QTY"].Caption = "到货量";
                gridView1.Columns["ARRIVED_QTY"].FieldName = "ARRIVED_QTY";
                gridView1.Columns["ARRIVED_QTY"].AppearanceHeader.ForeColor = Color.Red;
                if (gridView1.Columns["CUR_ARRIVE_QTY"] != null)
                {
                    gridView1.Columns["CUR_ARRIVE_QTY"].Visible = false;
                }
            }
        }

        private void SetPurchaseOrderCodes()
        {
            if (mListPurchaseOrders != null && mListPurchaseOrders.Count > 0)
            {
                txtPurchaseOrder.Tag = mListPurchaseOrders;
                txtPurchaseOrder.Text = "";
                foreach (PurPurchaseOrderEntity entity in mListPurchaseOrders)
                {
                    if (string.IsNullOrEmpty(txtPurchaseOrder.Text))
                    {
                        txtPurchaseOrder.Text = entity.PurchaseOrderCode;
                    }
                    else
                    {
                        txtPurchaseOrder.Text += "; " + entity.PurchaseOrderCode;
                    }
                }
            }
        }

        private void SetDataGridDetailByPurchaseOrders()
        {
            if (mListPurchaseOrders == null || mListPurchaseOrders.Count == 0)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr.RowState != DataRowState.Added)
                    {
                        PurPurchaseArrivedItemEntity entity = new PurPurchaseArrivedItemEntity(dr);
                        DeleteList.Add(entity);
                    }
                    dt.Rows.Remove(dr);
                }
            }
            else
            {
                BindDataGridDetail();
            }
            foreach (PurPurchaseOrderEntity purchase in mListPurchaseOrders)
            {
                List<PurPurchaseOrderItemEntity> list = PurPurchaseOrderItemBs.GetByPurchaseOrderID(purchase.PurchaseOrderId);
                foreach (PurPurchaseOrderItemEntity entity in list)
                {
                    DataRow dr = dt.NewRow();
                    dr["PURCHASE_ORDER_CODE"] = purchase.PurchaseOrderCode;
                    dr["ARRIVED_ITEM_ID"] = Guid.NewGuid().ToString();
                    dr["ARRIVED_ID"] = SelectedPurchaseArrived.ArrivedId;
                    dr["PURCHASE_ITEM_ID"] = entity.PurchaseItemId;
                    dr["QTY"] = entity.Qty;
                    dr["ARRIVED_QTY"] = 0;
                    MstProductEntity product = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                    if (product != null)
                    {
                        dr["PRODUCT_ID"] = product.ProductId;
                        dr["PRODUCT_CODE"] = product.ProductCode;
                        dr["PRODUCT_NAME"] = product.ProductName;
                        dr["PRODUCT_SPEC_IN"] = product.ProductSpecIn;
                        dr["MATERIAL"] = product.Material;
                        dr["UNIT"] = product.Unit;
                        dr["PRICE_NO_TAX"] = decimal.Round(entity.PriceNoTax, 2);
                        dr["TOTAL_AMOUNT"] = decimal.Round(entity.PriceNoTax * entity.Qty, 2);
                        dr["DESCRIPTION"] = product.Description;
                    }
                    dt.Rows.Add(dr);

                }
            }
            gvMain.DataSource = dt;
            ResetTotalAmount();
        }

        private void SetPurchaseOrderFields(bool setDetail)
        {
            if (mListPurchaseOrders == null || mListPurchaseOrders.Count == 0)
            {
                return;
            }
            SetPurchaseOrderCodes();
            foreach (PurPurchaseOrderEntity purOrder in mListPurchaseOrders)
            {
                if (purOrder == null)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(purOrder.SupplierId) == false)
                {
                    MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(purOrder.SupplierId);
                    if (supplier != null)
                    {
                        txtSupplier.Tag = supplier;
                        txtSupplier.Text = supplier.SupplierName;
                        txtSupplierContact.Text = supplier.Contact;
                        txtSupplierContactPhone.Text = supplier.ContactPhone;
                    }
                }
                if (string.IsNullOrEmpty(purOrder.PurchasePerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(purOrder.PurchasePerson);
                    if (person != null)
                    {
                        txtPurchasePerson.Tag = person;
                        txtPurchasePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
                if (string.IsNullOrEmpty(purOrder.ApprovedBy) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(purOrder.ApprovedBy);
                    if (person != null)
                    {
                        txtNeedApprovedPerson.Tag = person;
                        txtNeedApprovedPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
                if (string.IsNullOrEmpty(purOrder.QuoteOrderId) == false)
                {
                    PurQuoteOrderEntity quoteOrder = PurQuoteOrderBs.GetPurQuoteOrderByID(purOrder.QuoteOrderId);
                    if (quoteOrder != null)
                    {
                        txtQuoteOrder.Tag = quoteOrder;
                        txtQuoteOrder.Text = quoteOrder.QuoteOrderCode;
                    }
                }
                txtTotalAmount.Text = purOrder.TotalAmount.ToString();
                dtpDeliveryRequiredDate.EditValue = purOrder.DeliveryRequiredDate;
                dtpDeliveryPlanDate.EditValue = purOrder.DeliveryPlanDate;
                dtpPurchaseDate.EditValue = purOrder.PurchaseDate;
                cmbStatus.SetSelectedValue(purOrder.Status);
                break;
            }
            if (setDetail)
            {
                string sCondition = " and PURCHASE_ORDER_CODE like (";
                sCondition += "'%" + mListPurchaseOrders[0].PurchaseOrderCode + "%')";
                DataTable dt = PurPurchaseArrivedBs.GetByCondition(sCondition);
                if (dt != null && dt.Rows.Count != 0)
                {
                    int nIndex = 0;
                    DataTable dtArriveOrderDetail = new DataTable();
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataTable dtArriveOrderItem = PurPurchaseArrivedItemBs.GetDataSetByPurchaseArrivedID(dr["ARRIVED_ID"].ToString()).Tables[0];
                        if (dtArriveOrderItem.Rows.Count == 0)
                        {
                            gvMain.DataSource = null;
                            return;

                        }
                        if (nIndex == 0)
                        {
                            DataColumn dc = new DataColumn("ARRIVED_HISTORY_QTY", typeof(decimal));
                            dtArriveOrderItem.Columns.Add(dc);
                            dtArriveOrderDetail = dtArriveOrderItem.Clone();
                            for (int i = 0; i < dtArriveOrderItem.Rows.Count; i++)
                            {
                                DataRow drArriveOrderDetail = dtArriveOrderDetail.NewRow();
                                for (int j = 0; j < dtArriveOrderItem.Columns.Count; j++)
                                {
                                    drArriveOrderDetail[j] = dtArriveOrderItem.Rows[i][j];
                                }
                                drArriveOrderDetail["ARRIVED_ITEM_ID"] = Guid.NewGuid().ToString();
                                drArriveOrderDetail["ARRIVED_ID"] = SelectedPurchaseArrived.ArrivedId;
                                drArriveOrderDetail["ARRIVED_QTY"] = 0;
                                drArriveOrderDetail["ARRIVED_HISTORY_QTY"] = dtArriveOrderItem.Rows[i]["ARRIVED_QTY"];
                                dtArriveOrderDetail.Rows.Add(drArriveOrderDetail);
                            }
                            nIndex++;
                            continue;
                        }
                        else
                        {
                            for (int i = 0; i < dtArriveOrderDetail.Rows.Count; i++)
                            {
                                DataRow[] arryDr = dtArriveOrderItem.Select("PRODUCT_ID='" + dtArriveOrderDetail.Rows[i]["PRODUCT_ID"].ToString() + "'");
                                if (arryDr != null)
                                {
                                    dtArriveOrderDetail.Rows[i]["ARRIVED_HISTORY_QTY"] = Convert.ToDecimal(dtArriveOrderDetail.Rows[i]["ARRIVED_HISTORY_QTY"].ToString()) + Convert.ToDecimal(arryDr[0]["ARRIVED_QTY"].ToString());
                                }
                            }
                        }
                        nIndex++;
                    }
                    gvMain.DataSource = dtArriveOrderDetail;
                }
                else
                {
                    SetDataGridDetailByPurchaseOrders();
                }
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PURST", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", false);
        }

        private void BindDataGridDetail()
        {
            string purchaseArrivedId = "";
            if (SelectedPurchaseArrived != null)
            {
                purchaseArrivedId = SelectedPurchaseArrived.ArrivedId;
            }
            DataSet ds = PurPurchaseArrivedItemBs.GetDataSetByPurchaseArrivedID(purchaseArrivedId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            DataColumn colCurArriveQty = new DataColumn("CUR_ARRIVE_QTY", typeof(decimal));
            colCurArriveQty.DefaultValue = 0;
            dt.Columns.Add(colCurArriveQty);
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<PurPurchaseArrivedItemEntity>();
        }

        private void ResetTotalAmount()
        {
            decimal totalAmount = 0;
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt == null)
            {
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRICE_NO_TAX"].ToString()) == false
                    && string.IsNullOrEmpty(dr["ARRIVED_QTY"].ToString()) == false)
                {
                    decimal qty = Convert.ToDecimal(dr["ARRIVED_QTY"].ToString());
                    decimal price = Convert.ToDecimal(dr["PRICE_NO_TAX"].ToString());
                    totalAmount += qty * price;
                }
            }
            txtTotalAmount.Text = decimal.Round(totalAmount, 2).ToString();
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedPurchaseArrived == null)
            {
                return;
            }
            txtArrivedCode.Text = SelectedPurchaseArrived.ArrivedCode;
            if (string.IsNullOrEmpty(txtArrivedCode.Text))
            {
                txtArrivedCode.Text = "自动生成";
            }
            dtpArrivedDate.EditValue = SelectedPurchaseArrived.ArrivedDate;
            txtRemark.Text = SelectedPurchaseArrived.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedPurchaseArrived.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedPurchaseArrived.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedPurchaseArrived.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedPurchaseArrived.LastModifiedBy);
        }

        private void SetEntity()
        {
            if (dtpArrivedDate.EditValue != null)
            {
                SelectedPurchaseArrived.ArrivedDate = (DateTime)dtpArrivedDate.EditValue;
            }
            SelectedPurchaseArrived.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedPurchaseArrived.CreatedDate = DateTime.Now;
                SelectedPurchaseArrived.CreatedBy = CommonParameter.CurrentUser.PersonId;
                SelectedPurchaseArrived.IsQualitychecked = 0;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedPurchaseArrived.LastModifiedDate = DateTime.Now;
                SelectedPurchaseArrived.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (dtpArrivedDate.EditValue == null)
            {
                MessageBox.Show("到货日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("到货明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (CheckGrid() == false)
            {
                return false;
            }
            return true;
        }

        private bool CheckGrid()
        {
            if (gvMain.DataSource == null)
            {
                return true;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (DataRow dr in dt.Rows)
            {
                decimal purchaseQty = CommonFunctions.ToDecimal(dr["QTY"]);
                decimal totalArrivedQty = CommonFunctions.ToDecimal(dr["TOTAL_ARRIVED_QTY"]);
                decimal thisArrivedQty = CommonFunctions.ToDecimal(dr["ARRIVED_QTY"]);
                if (ThisActionType == ActionType.New)
                {
                    if (purchaseQty < totalArrivedQty + thisArrivedQty)
                    {
                        MessageBox.Show("到货数量不能超过采购数量！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                if (thisArrivedQty == 0)//+
                {
                    MessageBox.Show("到货数量不能为0！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    if (purchaseQty < thisArrivedQty)
                    {
                        MessageBox.Show("到货数量不能超过采购数量！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurPurchaseArrivedBs.SavePurchaseArrived(true, SelectedPurchaseArrived, mListPurchaseOrders, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurPurchaseArrivedBs.SavePurchaseArrived(false, SelectedPurchaseArrived, mListPurchaseOrders, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            if (mListPurchaseOrders != null && mListPurchaseOrders.Count > 0)
            {
                if (ThisActionType == ActionType.New)
                {
                    SetPurchaseOrderFields(true);
                }
                else
                {
                    SetPurchaseOrderFields(false);
                }
            }
            Init();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                SendMessageToQc("新质检任务！", CommonParameter.CurrentUser.PersonId, "新到货单：'" + SelectedPurchaseArrived.ArrivedCode + "'已产生，请进行质检！", MessageLevel.ML03.ToString());
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedPurchaseArrived = new PurPurchaseArrivedEntity();
                SelectedPurchaseArrived.ArrivedId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        private void txtPurchaseOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseOrderQuery frm = new frmMaintainPurchaseOrderQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurchaseOrders != null)
            {
                mListPurchaseOrders = frm.SelectedPurchaseOrders;
                SetPurchaseOrderFields(true);
            }
            else
            {
                txtPurchaseOrder.Text = "";
                txtPurchaseOrder.Tag = null;
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("ARRIVED_QTY"))
            {
                DataTable dt = gvMain.DataSource as DataTable;
                decimal unitPrice = 0;
                if (string.IsNullOrEmpty(dt.Rows[e.RowHandle]["PRICE_NO_TAX"].ToString()) == false)
                {
                    unitPrice = Convert.ToDecimal(dt.Rows[e.RowHandle]["PRICE_NO_TAX"].ToString());
                }
                decimal qty = 0;
                if (string.IsNullOrEmpty(dt.Rows[e.RowHandle]["ARRIVED_QTY"].ToString()) == false)
                {
                    qty = Convert.ToDecimal(dt.Rows[e.RowHandle]["ARRIVED_QTY"].ToString());
                }
                dt.Rows[e.RowHandle]["TOTAL_AMOUNT"] = unitPrice * qty;
                ResetTotalAmount();
            }
        }

        private void SendMessageToQc(string sMessageTitle, string sSender, string sMessageBody, string MessageLevel)
        {
            MstMessageEntity message = new MstMessageEntity();
            message.MessageId = Guid.NewGuid().ToString();
            message.MessateTitle = sMessageTitle;
            message.MessageSender = sSender;
            message.MessageBody = sMessageBody;
            message.MessageLevel = MessageLevel;
            message.FormName = "ESOL.WinUI.Qc.frmQcOverview";
            message.MessageDate = DateTime.Now;//btnModify
            List<MstPersonEntity> toList = SecUserBs.GetPersonIdByFormAndObject("frmQcOverview", "新增", "btnAdd");
            MstMessageBs.SendMessage(message, toList);
        }

        #endregion


    }
}
